package com.yunqiao.api.controller;

import cn.hutool.core.lang.Dict;
import cn.hutool.core.util.StrUtil;
import com.aliyuncs.exceptions.ClientException;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yunqiao.api.annotation.Login;
import com.yunqiao.api.utils.HttpClientUtil;
import com.yunqiao.api.utils.JwtUtils;
import com.yunqiao.common.exception.CustomApiException;
import com.yunqiao.common.pay.WxPay;
import com.yunqiao.common.utils.ApiResponse;
import com.yunqiao.common.utils.PageUtils;
import com.yunqiao.common.validator.ValidatorUtils;
import com.yunqiao.service.api.UserService;
import com.yunqiao.service.api.entity.ApplyDriverEntity;
import com.yunqiao.service.api.entity.UserEntity;
import com.yunqiao.service.api.vo.UserVo;
import com.yunqiao.service.sys.SysUserService;
import com.yunqiao.service.sys.entity.SysUserEntity;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * 用户信息
 * @author Crocutax
 * @email wangxw725@163.com
 * @date 2019-03-03 21:58:56
 */
@RestController
@RequestMapping("api/user")
@Api(tags = "UserApiController" ,description = "用户信息管理")
public class UserApiController {

    @Autowired
    private UserService userService;

    @Autowired
    private JwtUtils jwtUtils;
    @Autowired
    private SysUserService sysUserService;

    /**
     * 列表
     */
    @ApiImplicitParams({
        @ApiImplicitParam(name = "roleType", value = "角色类型:1 用户 2司机", required = false,allowableValues = "1,2",paramType = "query" , dataType = "int"),
        @ApiImplicitParam(name = "superiorUserId", value = "上级ID", required = false ,paramType = "query" , dataType = "int"),
        @ApiImplicitParam(name = "page", value = "页码", required = false ,defaultValue = "1",paramType = "query" , dataType = "int"),
        @ApiImplicitParam(name = "limit", value = "数量", required = false,defaultValue = "10",paramType = "query" , dataType = "int")
    })
    @GetMapping("/list")
    @ApiOperation("查询用户信息 列表")
    public ApiResponse<PageUtils<UserEntity>> list(@ApiIgnore @RequestParam Map<String, Object> params){
        PageUtils page = userService.queryPage(params);
        return new ApiResponse<>(page);
    }

    /**
     * 信息
     */
    @GetMapping("/info/{id}")
    @ApiOperation("查询单个用户信息")
    public ApiResponse<UserEntity> info(@PathVariable("id") Long id){
        if (id == null) {
            throw new CustomApiException("ID不能为空");
        }
        UserEntity user = userService.details(id);
        return new ApiResponse<>(user);
    }

    /**
     * 保存
     */
    @Login
    @PostMapping("/save")
    @ApiOperation("保存用户信息")
    public ApiResponse save(UserEntity user){
        ValidatorUtils.validateEntity(user);
        userService.save(user);
        return new ApiResponse<>();
    }


    /**
     * 修改
     */
    @Login
    @PutMapping("/update/{id}")
    @ApiOperation("修改用户信息")
    public ApiResponse update(@PathVariable Long id , @RequestBody UserEntity user){
        UserEntity dbItem = userService.getById(id);
        if(dbItem==null){
            throw new CustomApiException("ID有误, 未找到对应数据");
        }
        user.setId(id);
        userService.updateById(user);
        return new ApiResponse<>();
    }

    /**
     * 删除
     */
    @Login
    @DeleteMapping("/delete/{id}")
    @ApiOperation("删除用户信息")
    public ApiResponse delete(@PathVariable Long id){
        if (id == null) {
            throw new CustomApiException("ID不能为空");
        }
        userService.removeById(id);
        return new ApiResponse<>();
    }

    /**
     * 获取推荐的用户列表
     */
    @ApiImplicitParam(name = "superiorUserId", value = "用户id", required = false, paramType = "query" , dataType = "long")
    @Login
    @GetMapping("/getSuperiorUserUser")
    @ApiOperation("获取推荐的用户列表")
    public ApiResponse<List<UserVo>> getSuperiorUserUser(Long superiorUserId){
        if (superiorUserId == null) {
            throw new CustomApiException("ID不能为空");
        }
        List<UserVo> list  = userService.getSuperiorUserUser(superiorUserId);
        return new ApiResponse<>(list);
    }


    /**
     * 申请退押金
     */
    @ApiImplicitParam(name = "id", value = "用户id", required = false, paramType = "query" , dataType = "long")
    @Login
    @GetMapping("/depositRefund")
    @ApiOperation("申请退押金")
    public ApiResponse<List<UserVo>> depositRefund(Long id) throws Exception {
        if (id == null) {
            throw new CustomApiException("ID不能为空");
        }
        userService.depositRefund(id);
        return new ApiResponse<>();
    }

    /**
     * 申请成为司机
     */
    @Login
    @PostMapping("/applyDriver")
    @ApiOperation("申请成为司机")
    public ApiResponse applyDriver(@RequestBody ApplyDriverEntity applyDriver){
        userService.applyDriver(applyDriver);
        return new ApiResponse<>();
    }

    /**
     * 获取申请成为司机的资料
     */
    @ApiImplicitParam(name = "id", value = "用户id", required = false, paramType = "query" , dataType = "long")
    @GetMapping("/getApplyDriverDetails")
    @ApiOperation("获取申请成为司机的资料")
    public ApiResponse<ApplyDriverEntity> getApplyDriverDetails(Long userId){
        ApplyDriverEntity applyDriverEntity = userService.getApplyDriverDetails(userId);
        return new ApiResponse<>(applyDriverEntity);
    }

    /**
     * 获取用户经纬度
     */
    @ApiImplicitParam(name = "id", value = "用户id", required = false, paramType = "query" , dataType = "long")
    @GetMapping("/getUserLocation")
    @ApiOperation("获取用户经纬度")
    public ApiResponse<Map> getUserLocation(Long id){
        UserEntity userEntity = userService.getById(id);
        Map<String, Object> map = new HashMap<>();
        map.put("longitude", userEntity.getLongitude());
        map.put("latitude", userEntity.getLatitude());
        return new ApiResponse<>(map);
    }

    /**
     * 司机收车 不接单
     */
    @ApiImplicitParam(name = "id", value = "用户id", required = false, paramType = "query" , dataType = "long")
    @Login
    @PutMapping("/driverOff/{id}")
    @ApiOperation("司机收车 不接单")
    public ApiResponse driverOff(@PathVariable Long id){
        this.userService.driverOff(id);
        return new ApiResponse<>();
    }

    /**
     * 司机开启接单
     */
    @ApiImplicitParam(name = "id", value = "用户id", required = false, paramType = "query" , dataType = "long")
    @Login
    @PutMapping("/driverOpen/{id}")
    @ApiOperation("司机开启接单")
    public ApiResponse driverOpen(@PathVariable Long id){
        return new ApiResponse<>(this.userService.driverOpen(id));
    }
    /**
     * 用户授权登录
     */
    @ApiImplicitParam(name = "openId", value = "微信唯一标识", required = false, paramType = "query" , dataType = "String")
    @PostMapping("/wxAuth")
    @ApiOperation("用户授权登录")
    public ApiResponse<Map<String, Object>> wxAuth(@RequestBody Dict dict){
        UserEntity userEntity = this.userService.auth(dict.getStr("openId"));
        //生成token
        String token = jwtUtils.generateToken(userEntity.getRoleType(),userEntity.getId());

        Map<String, Object> map = new HashMap<>();
        map.put("token", token);
        map.put("expire", jwtUtils.getExpire());
        map.put("userId", userEntity.getId());
        map.put("isSetDetails", StrUtil.isNotBlank(userEntity.getName()));
        return new ApiResponse<>(map);
    }

    /**
     * 用户授权登录
     */
    @ApiImplicitParam(name = "openId", value = "qq唯一标识", required = false, paramType = "query" , dataType = "String")
    @PostMapping("/qqAuth")
    @ApiOperation("用户授权登录")
    public ApiResponse<Map<String, Object>> qqAuth(@RequestBody Dict dict){
        UserEntity userEntity = this.userService.qqAuth(dict.getStr("openId"));
        //生成token
        String token = jwtUtils.generateToken(userEntity.getRoleType(),userEntity.getId());
        Map<String, Object> map = new HashMap<>();
        map.put("token", token);
        map.put("expire", jwtUtils.getExpire());
        map.put("userId", userEntity.getId());
        map.put("isSetDetails", StrUtil.isNotBlank(userEntity.getName()));
        return new ApiResponse<>(map);
    }

    /**
     * 判断qq openid是否已注册
     */
    @ApiImplicitParam(name = "openId", value = "qq唯一标识", required = false, paramType = "query" , dataType = "String")
    @GetMapping("/qqOppenidIsRegister")
    @ApiOperation("判断qq openid是否已注册")
    public ApiResponse<Boolean> qqOppenidIsRegister(String openId){
        int count = this.userService.count(new QueryWrapper<UserEntity>().eq("qq_openid", openId));
        return new ApiResponse<>(count > 0);
    }

    /**
     * 判断wx openid是否已注册
     */
    @ApiImplicitParam(name = "openId", value = "qq唯一标识", required = false, paramType = "query" , dataType = "String")
    @GetMapping("/wxOppenidIsRegister")
    @ApiOperation("判断wx openid是否已注册")
    public ApiResponse<Boolean> wxOppenidIsRegister(String openId){
        int count = this.userService.count(new QueryWrapper<UserEntity>().eq("wx_openid", openId));
        return new ApiResponse<>(count > 0);
    }

    /**
     * 创建账号代理商账号
     */
    @ApiImplicitParam(name = "userId", value = "用户", required = false, paramType = "query" , dataType = "Long")
    @PostMapping("/createUser/{id}")
    @ApiOperation("创建账号代理商账号")
    public ApiResponse<SysUserEntity> createUser(@PathVariable Long id) throws ClientException {
        SysUserEntity sysUserEntity = sysUserService.createUser(id);
        return new ApiResponse<>(sysUserEntity);
    }

    /**
     * 小程序微信授权登陆
     */
    @ApiImplicitParam(name = "authCode", value = "授权code", required = false, paramType = "query" , dataType = "String")
    @PostMapping("/getWxOpenId")
    @ApiOperation("获取微信openId")
    public ApiResponse<Map<String, Object>> getWxOpenId(String authCode,Integer type) throws ClientException {
        String appId="";
        String appsecret = "";
        if(type==1){
            appId = WxPay.wx_small_procedures_user_appid;
            appsecret = WxPay.wx_small_procedures_user_appsecret;
        }else {
            appId = WxPay.wx_small_procedures_driver_appid;
            appsecret = WxPay.wx_small_procedures_driver_appsecret;
        }
        Map<String, Object> map =getOpenId(authCode, appId,appsecret);
        return new ApiResponse<>(map);
    }
    private  Map<String, Object> getOpenId(String code,String appId,String appsecret){
        Map<String, Object> ret = new HashMap<>();
        // 组装参数*****
        Map<String, String> urlData= new HashMap<String, String>();
        urlData.put("appid",appId);//小程序id
        urlData.put("secret",appsecret);//小程序key
        urlData.put("grant_type","authorization_code");//固定值这样写就行
        urlData.put("js_code",code);//小程序传过来的code
        Map<String, Object> data = null;
        try {
            String code2OpenidUrl="https://api.weixin.qq.com/sns/jscode2session";
            data= HttpClientUtil.doPost(code2OpenidUrl, urlData);
        }catch(Exception ex){
            ret.put("success", false);
            ret.put("msg", "_getOpenId_未知异常");
            ret.put("message", ex);
            return ret;
        }
        if(data.containsKey("errcode") ){
            ret.put("success", false);
            ret.put("msg", data.get("errcode"));
            ret.put("message", data.get("errmsg"));
        }else{
            ret.put("success", true);
            ret.put("result",data);
        }
        return ret;
    }
}
